import modelExtend from 'dva-model-extend'
import { routerRedux } from 'dva/router'
import { pageModel } from '@/common/model/BaseModel'
import {
  getScrapList,
  delPropScrap,
  getPropScrapDetail,
  saveScrapUpdate,
} from '../services/property'

export default modelExtend(pageModel, {
  namespace: 'propScrap',
  state: {
    currentItem: {},
    selectedRowKeys: [],
    formValues: {},
    //
    showProps: false,
    //
    showView: false,
    //
    currentSteps: [],
  },
  effects: {
    *fetchList({ payload }, { call, put }) {
      console.log('fetchScrapList')
      const res = yield call(getScrapList, payload || {})
      yield put({
        type: 'updateState',
        payload: {
          list: res.data.records,
          pagination: {
            showSizeChanger: false,
            showQuickJumper: true,
            showTotal: total => `共 ${total} 条`,
            total: res.data.total,
            current: res.data.current,
            pageSize: res.data.size,
          },
          formValues: payload,
        },
      })
    },
    *remove({ payload }, { call, put, select }) {
      const res = yield call(delPropScrap, payload)
      if (res && res.success) {
        yield put({
          type: 'updateState',
          payload: {
            selectedRowKeys: [],
          },
        })
        const formValues = yield select(state => state.formValues)
        yield put({
          type: 'fetchList',
          payload: {
            current: 1,
            ...formValues,
          },
        })
      }
    },
    *edit({ payload }, { call, put }) {
      //
      const res = yield call(getPropScrapDetail, payload)
      if (res && res.success) {
        yield put({
          type: 'updateState',
          payload: {
            currentItem: res.data,
            currentSteps: res.tag ? res.tag.data || [] : [],
          },
        })
      }
    },
    *save({ payload }, { call, put }) {
      const res = yield call(saveScrapUpdate, payload)
      if (res && res.success) {
        yield put({
          type: 'updateState',
          payload: {
            currentItem: {},
          },
        })
        yield put(
          routerRedux.push({
            pathname: '/property/scrap',
          }),
        )
      }
    },
  },
})
